package com.teamclub.pay.scontrollers

import java.nio.charset.Charset

import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import io.ebean.Ebean
import com.teamclub.domain.pay.order.{PayInfoConf, PayOrder}
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.{PostMapping, RequestMapping, RestController}
import weixin.popular.bean.paymch.{MchBaseResult, MchPayNotify}
import weixin.popular.support.expirekey.DefaultExpireKey
import weixin.popular.util.{SignatureUtil, StreamUtils, XMLConverUtil}

@RestController("com.teamclub.pay.scontrollers.NotifyController")
@RequestMapping(Array("/pay"))
class NotifyController {
  val logger = LoggerFactory.getLogger(classOf[NotifyController])
  val expireKey = new DefaultExpireKey()

  @PostMapping(Array("receiveNotify"))
  def receiveNotify(request: HttpServletRequest, response: HttpServletResponse): Unit = {
    // 获取请求数据
    val xmlData = StreamUtils.copyToString(request.getInputStream, Charset.forName("utf-8"))
    logger.info("notify data: {}", xmlData)
    val mapData = XMLConverUtil.convertToMap(xmlData)
    val payNotify = XMLConverUtil.convertToObject(classOf[MchPayNotify], xmlData)
    if(expireKey.exists(payNotify.getTransaction_id)) {
      return ;
    }
//    payNotify.buildDynamicField(mapData)
    try {
      val appid = mapData.get("appid")
      val appKey = Ebean.find(classOf[PayInfoConf]).where().eq("thirdAppId", appid).findOne().getThirdAppKey
      if (SignatureUtil.validateSign(mapData, appKey)) {
        expireKey.add(payNotify.getTransaction_id)
        try {
          val payOrder = Ebean.find(classOf[PayOrder]).where().eq("orderNum", payNotify.getOut_trade_no).findOne()
          payOrder.setThirdOrderNum(payNotify.getTransaction_id)
          payOrder.setPayResult(1);
          payOrder.setPayResultMsg("支付成功")
          payOrder.update()
        } catch {
          case e: Exception => {
            logger.warn("", e)
            val baseResult = new MchBaseResult
            baseResult.setReturn_code("FAIL")
            baseResult.setReturn_msg("ERROR")
            response.getOutputStream.write(XMLConverUtil.convertToXML(baseResult).getBytes)
            return ;
          }
        }

        val baseResult = new MchBaseResult
        baseResult.setReturn_code("SUCCESS")
        baseResult.setReturn_msg("OK")
        response.getOutputStream.write(XMLConverUtil.convertToXML(baseResult).getBytes)
      }
      else {
        logger.warn("sign 不一致")
        val baseResult = new MchBaseResult
        baseResult.setReturn_code("FAIL")
        baseResult.setReturn_msg("Sign不一致")
        response.getOutputStream.write(XMLConverUtil.convertToXML(baseResult).getBytes)
      }
    } catch {
      case e: Exception => {
        logger.warn("获取signKey  失败")
        val baseResult = new MchBaseResult
        baseResult.setReturn_code("FAIL")
        baseResult.setReturn_msg("获取signKey  失败")
        response.getOutputStream.write(XMLConverUtil.convertToXML(baseResult).getBytes)
      }
    }


  }
}
